package cn.edu.gzhu.workOrderManagement.service.impl;

import cn.edu.gzhu.workOrderManagement.mapper.OrganizationMapper;
import cn.edu.gzhu.workOrderManagement.pojo.dto.organization.OrganizationDeleteDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.organization.OrganizationListDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.organization.OrganizationRegisterDto;
import cn.edu.gzhu.workOrderManagement.pojo.dto.organization.OrganizationUpdateDto;
import cn.edu.gzhu.workOrderManagement.pojo.entity.Organization;
import cn.edu.gzhu.workOrderManagement.pojo.vo.OrganizationListVo;
import cn.edu.gzhu.workOrderManagement.service.OrganizationService;
import cn.edu.gzhu.workOrderManagement.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper,Organization> implements OrganizationService {
    @Autowired
    UserService userService;
    /**
     * 注册组织
     *
     * @param organizationRegisterDto
     * @return
     */
    @Override
    public Boolean saveOrganization( OrganizationRegisterDto organizationRegisterDto) {
        Organization organization = new Organization();
        //组织初始为不可用
        organization.setIsAvailable(false);
        BeanUtils.copyProperties(organizationRegisterDto, organization);
        organization.setCreateTime(LocalDateTime.now());
        organization.setUpdateTime(LocalDateTime.now());
        return this.save(organization);
    }

    /**
     * 按条件修改组织属性
     *
     * @param organizationUpdateDto
     * @return
     */
    @Override
    public Boolean updateOrganization(OrganizationUpdateDto organizationUpdateDto) {

        LambdaUpdateWrapper<Organization> updateWrapper = new LambdaUpdateWrapper<>();

        // 这里的 set() 只有在字段非空时才会添加更新字段
        updateWrapper.eq(Organization::getName, organizationUpdateDto.getName());

        if (StringUtils.isNotBlank(organizationUpdateDto.getName())) {
            updateWrapper.set(Organization::getName, organizationUpdateDto.getName());
        }
        if (organizationUpdateDto.getCapacity() != null) {
            updateWrapper.set(Organization::getCapacity, organizationUpdateDto.getCapacity());
        }
        if (organizationUpdateDto.getIsAvailable() != null) {
            updateWrapper.set(Organization::getIsAvailable, organizationUpdateDto.getIsAvailable());
        }
        updateWrapper.set(Organization::getUpdateTime, LocalDateTime.now());
        return this.update(updateWrapper);
    }

    /**
     * 按条件分页列出组织
     *
     * @param organizationListDto
     * @return
     */
    @Override
    public IPage<OrganizationListVo> listOrganizationsByConditions(OrganizationListDto organizationListDto) {
        LambdaQueryWrapper<Organization> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.isNotBlank(organizationListDto.getName())) {
            queryWrapper.like(Organization::getName, organizationListDto.getName());
        }
        if (organizationListDto.getIsAvailable() != null) {
            queryWrapper.eq(Organization::getIsAvailable, organizationListDto.getIsAvailable());
        }
        if (organizationListDto.getCapacity() != null) {
            queryWrapper.eq(Organization::getCapacity, organizationListDto.getCapacity());
        }
        if (organizationListDto.getIsHead()!=null){
            queryWrapper.eq(Organization::getIsHead,organizationListDto.getIsHead());
        }
        // 直接使用 this.page() 进行分页查询
        Page<Organization> page = new Page<>(organizationListDto.getStartPage(), organizationListDto.getPageSize());
        IPage<Organization> organizationIPage = this.page(page, queryWrapper);
        List<OrganizationListVo> voList =organizationIPage.getRecords().stream()
                .map(org -> {
                    OrganizationListVo vo = new OrganizationListVo();
                    BeanUtils.copyProperties(org, vo);
                    return vo;
                }).collect(Collectors.toList());

        // **使用 MyBatis-Plus 的 Page 对象构造 IPage**
        IPage<OrganizationListVo> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 根据名字删除组织
     *
     * @param organizationDeleteDto
     * @return
     */
    @Override

    public Boolean deleteOrganization(OrganizationDeleteDto organizationDeleteDto) {
        // 组织中若还有用户，则一起删除所有该组织用户
        List<String> names = organizationDeleteDto.getNames();

        for (String name : names){
           userService.deleteUsersByOrganization(name);
        }

        // 2️⃣ 再删除组织
        int deletedCount = this.baseMapper.delete(new LambdaQueryWrapper<Organization>()
                .in(Organization::getName, names));

        return deletedCount > 0; // 返回是否成功删除

    }
}
